package com.phone.store.controller;

import com.phone.store.exception.PhoneException;
import com.phone.store.form.AddressForm;
import com.phone.store.service.AddressService;
import com.phone.store.util.ResultVOUtil;
import com.phone.store.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * @author fangyu
 * @version v1.0.0
 * @date 2020/7/31 10:06 下午
 */
@Slf4j
@RestController
@RequestMapping("/address")
public class AddressController {

    @Autowired
    private AddressService addressService;

    @GetMapping("/list")
    public ResultVO list() {
        return ResultVOUtil.success(addressService.findAll());
    }

    @PostMapping("/create")
    public ResultVO create(
            @Valid @RequestBody AddressForm addressForm,
            BindingResult bindingResult
    ) {
        if (bindingResult.hasErrors()) {
            log.error("【添加地址】参数错误,addressForm={}", addressForm);
            throw new PhoneException(bindingResult.getFieldError().getDefaultMessage());
        }

        addressService.saveOrUpdateAddress(addressForm);
        return ResultVOUtil.success(null);
    }

    @PutMapping("/update")
    public ResultVO update(
            @Valid @RequestBody AddressForm addressForm,
            BindingResult bindingResult
    ) {
        if (bindingResult.hasErrors()) {
            log.error("【修改地址】参数错误,addressForm={}", addressForm);
            throw new PhoneException(bindingResult.getFieldError().getDefaultMessage());
        }

        addressService.saveOrUpdateAddress(addressForm);
        return ResultVOUtil.success(null);
    }
}
